package com.deer.wms.base.system.web.bill;

import com.deer.wms.base.system.model.bill.*;
import com.deer.wms.base.system.model.item.ItemInfo;
import com.deer.wms.base.system.model.ware.Supplier;
import com.deer.wms.base.system.service.bill.BillInSapService;
import com.deer.wms.base.system.service.bill.IBillInMasterService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.item.IItemInfoService;
import com.deer.wms.base.system.service.ware.ISupplierService;
import com.deer.wms.base.system.service.zh.WorkTasksService;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.common.core.text.Convert;
import com.deer.wms.common.exception.ServiceException;
import com.deer.wms.common.utils.poi.ExcelUtil;
import com.deer.wms.framework.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**SAP入库单据*/
@Controller
@RequestMapping("/in/billInSap")
public class BillInSapController extends BaseController {

    private String prefix = "in/billInSap";

    @Autowired//SAP
    private BillInSapService billInSapService;
    @Autowired//入库
    private IBillInMasterService iBillInMasterService;
    @Autowired//厂家
    private ISupplierService supplierService;
    @Autowired//物料
    private IItemInfoService itemInfoService;
    @Autowired //工作任务
    private WorkTasksService workTasksService;
    @Autowired //库存
    private IBoxItemService boxItemService;

    /*明细跳转*/
    //@RequiresPermissions("in:billInSapDetail:view")
    @GetMapping("/billInSapDetailPage")
    public String billInSapDetail() {
        return prefix + "/billInSapDetail";
    }

    /*SAP入库单明细列表*/
    @PostMapping("/detailList")
    @ResponseBody
    public TableDataInfo detailList(BillInSapDetailDto billInSapDetailDto) {
        startPage();
        List<BillInSapDetailDto> billInSapDetailList = billInSapService.findBillInSapDetailList(billInSapDetailDto);
        return getDataTable(billInSapDetailList);
    }

    /*SAP入库单列表*/
    // @RequiresPermissions("in:billInSap:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BillInSap billInSap) {
        startPage();
        List<BillInSap> billInSapList = billInSapService.findBillInSapList(billInSap);
        return getDataTable(billInSapList);
    }

    /*根据id找sap单*/
    @PostMapping("/findBillInSapByBillInSapId")
    @ResponseBody
    public BillInSapDto findBillInSapByBillInSapId(Integer billInSapId){
        return billInSapService.findBillInSapByBillInSapId(billInSapId);
    }

    /*根据id找sap单明细*/
    @PostMapping("/findBillInSapDetailByBillInSapId")
    @ResponseBody
    public TableDataInfo findBillInSapDetailByBillInSapId(Integer billInSapId){
        List<BillInSapDetailDto> list = billInSapService.findBillInSapDetailByBillInSapId(billInSapId);
        return getDataTable(list);
    }
    /*删除单据*/
    @PostMapping("/detele")
    @ResponseBody
    @Transactional
    public AjaxResult remove(Integer id) {
        return toAjax(billInSapService.deleteSapByIds(id)+billInSapService.deleteSapDetailByIds(id));
    }

    /*审核跳转*/
    @GetMapping("/billInSapAudit")
    public String billInSapAudit() {
        return prefix + "/billInSapAudit";
    }
    /*手工建单的审核跳转*/
    @GetMapping("/billInSapAuditManual")
    public String billInSapAuditManual() {
        return prefix + "/billInSapAuditManual";
    }

    /*手工建单的审核提交*/
    @PostMapping("/auditManual")
    @ResponseBody
    @Transactional
    public Result auditSaveManual(@RequestBody BillInSap billInSap) {
        //添加SAP采购单
        billInSap.setBillState(2); //已审核
        billInSapService.updateBillInSap(billInSap);//sap
        String createUserName = ShiroUtils.getLoginName();
        billInSap.setCreateName(createUserName);

        iBillInMasterService.updateSapNoBySapId(billInSap);//入库单
        //库存解除冻结
        boxItemService.updateBySapId(billInSap.getBillInSapId());

        return ResultGenerator.genSuccessResult();
    }

    /*审核提交*/
    @PostMapping("/audit")
    @ResponseBody
    @Transactional
    public Result auditSave(@RequestBody BillInSap billInSap) {
        //改变sap单状态 已审核
        billInSap.setBillState(2);
        billInSapService.updateBillInSap(billInSap);
        //创建入库单
        Long inNumber = workTasksService.getBillInNumber();
        String billNo = "RK" + inNumber;
        String createUserName = ShiroUtils.getLoginName();
        BillInMaster billInMaster = new BillInMaster();
        billInMaster.setSapId(billInSap.getBillInSapId())
                .setSapNo(billInSap.getSapNo())//sap采购单号
                .setBillNo(billNo)//入库单号
                .setInNumber(inNumber)//流水号
                .setSupplierName(billInSap.getSupplierName())//供应商(英文)
                .setSupplierId(billInSap.getSupplierId())//供应商id
                .setState(1)//待入库
                .setSapState(1)//sap未过账
                .setType(billInSap.getType())//入库类型
                .setCreateUserName(createUserName)
                .setAuditUserName(createUserName);

        iBillInMasterService.insertBillInMaster(billInMaster);
        return ResultGenerator.genSuccessResult();
    }

    /*下载SAP模板*/
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate(){
        List<BillInSapDto> billInSapList =new ArrayList<>();
        ExcelUtil<BillInSapDto> util = new ExcelUtil<BillInSapDto>(BillInSapDto.class);

        return util.importTemplateExcel(billInSapList,"SAP入库单模板");
    }

    /*导入SAP模板*/
    @PostMapping("/importData")
    @ResponseBody
    @Transactional
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BillInSapDto> util = new ExcelUtil<BillInSapDto>(BillInSapDto.class);
        List<BillInSapDto> List = util.importExcel(file.getInputStream());
        java.util.List<BillInSapDto> electricBoxDetails = List.subList(2, List.size());

        //插入数据准备
        String userName = ShiroUtils.getLoginName();
        Integer userId = ShiroUtils.getUserId();
        BillInSapDto billInSapDto = List.get(2);

        //新建SAP入库单
        billInSapDto.setCreateName(userName)
                .setCreateId(userId)
                .setBillState(1).setState(1);
        billInSapService.insertBillInSap(billInSapDto);

        //添加SAP入库明细
        int sapId = billInSapDto.getBillInSapId();
        electricBoxDetails.forEach(el->{
            if(!el.getSapNo().equals("")){
                ItemInfo Item = itemInfoService.findByItemCode(el.getMATNR());
                if(Item == null){
                    throw new ServiceException(CommonCode.ITEMCODE_ERROR, "异常物料号:"+el.getMATNR());
                }
                el.setItemId(Item.getItemId()).setBillInSapId(sapId);
                billInSapService.insertBillInSapDetail(el);
            }
        });

        return AjaxResult.success("导入成功");
    }

    /*根据id强制过账*/
    @PostMapping("/sapPosting")
    @ResponseBody
    @Transactional
    public AjaxResult posting(@RequestBody BillInSap billInSap) {

        int billInSapId = billInSap.getBillInSapId();
        //1.查询所有未过账id
        List<Integer> idList = billInSapService.findStateDetailById(billInSapId);
        //2.拼接成str字符串
        String ids="";
        for (Integer id : idList) {
            ids = ids+id+",";
        }
        //3.调用导出方法
        List<BillInSapDetailVo> byIds = new ArrayList();
        BillInSapDetailVo billInSapDetailVo = new BillInSapDetailVo();
        SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
        String day = date.format(new Date());
        SimpleDateFormat batchDate = new SimpleDateFormat("yyyyMMdd");
        String batchDay = batchDate.format(new Date());
        int id = 0;
        int sum = 0;
        String[] split = ids.split(",");
        for (String s:split) {
            id = Integer.parseInt(s);
            BillInSapDetailDto BillInSapDetail = billInSapService.findBillInSapDetailVo(id);
            billInSapDetailVo.setPoNumber(BillInSapDetail.getSapNo())//采购凭证号
                    .setErfme(BillInSapDetail.getERFME()) //单位
                    .setErfmg(BillInSapDetail.getERFMG_RECEIVED()) //重量
                    .setLfsnr(BillInSapDetail.getSupplierName()+batchDay) //供应商+日期
                    .setAction("A01")
                    .setRefdoc("R01")
                    .setTvBwart(101)
                    .setBldat(day)
                    .setBudat(day)
                    .setZeile(1)
                    .setBwart(101)
                    .setLgobe("R003")
                    .setCharg(batchDay)
                    .setTake("X");
            byIds.add(billInSapDetailVo);
            //修改状态为已过帐
            billInSapService.updateDetailCarryStateById(id);
            //判断如果全部都过账,则SAP单已过帐
            sum = billInSapService.selectCarryStateCount(id);
            if(sum != 0){
                billInSapService.updateBillInSapState3(id); //部分
            }else {
                billInSapService.updateBillInSapState2(id); //已过账
            }

        }
        ExcelUtil<BillInSapDetailVo> util = new ExcelUtil<>(BillInSapDetailVo.class);
        return util.exportExcel(byIds, "SAP入库过账单据");
    }

    /*导出SAP,并改变过账状态为过账*/
    @RequiresPermissions("in:billInSap:partExcel")
    @PostMapping("/partExcel")
    @ResponseBody
    @Transactional
    public AjaxResult partExcel(@RequestParam  String ids) {
        List<BillInSapDetailVo> byIds = new ArrayList();
        SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
        String day = date.format(new Date());
        SimpleDateFormat batchDate = new SimpleDateFormat("yyyyMMdd");
        String batchDay = batchDate.format(new Date());
        int id = 0;
        int sum = 0;
        String[] split = ids.split(",");
        for (String s:split) {
            id = Integer.parseInt(s);
            BillInSapDetailDto BillInSapDetail = billInSapService.findBillInSapDetailVo(id);
            BillInSapDetailVo billInSapDetailVo = new BillInSapDetailVo();
            billInSapDetailVo.setPoNumber("")//采购凭证号
                    .setItemName(BillInSapDetail.getItemName())//规格
                    .setItemCode(BillInSapDetail.getItemCode())//物料编码
                    .setErfme(BillInSapDetail.getERFME()) //单位
                    .setErfmg(BillInSapDetail.getERFMG_RECEIVED()) //重量
                    .setLfsnr("123123123123")
                    .setAction("A01")
                    .setRefdoc("R01")
                    .setTvBwart(101)
                    .setBldat(day)
                    .setBudat(day)
                    .setZeile(1)
                    .setBwart(101)
                    .setLgobe("R003")
                    .setCharg(batchDay)
                    .setTake("X");
            byIds.add(billInSapDetailVo);
            //修改状态为已过帐
            billInSapService.updateDetailCarryStateById(id);
            //判断如果全部都过账,则SAP单已过帐
            sum = billInSapService.selectCarryStateCount(id);
            if(sum != 0){
                billInSapService.updateBillInMasterState3(id);
                billInSapService.updateBillInSapState3(id); //部分
            }else {
                billInSapService.updateBillInMasterState2(id);
                billInSapService.updateBillInSapState2(id); //已过账
            }

        }
        ExcelUtil<BillInSapDetailVo> util = new ExcelUtil<>(BillInSapDetailVo.class);
        return util.exportExcel(byIds, "SAP入库过账单据");
    }



    //打印
    @RequestMapping("print")
    public String print(@RequestParam String ids, Model model) {
        List<BillInSapDto> byIds=new ArrayList();
        String[] split = ids.split(",");
        for (String s:split
             ) {
            BillInSapCriteria b=new BillInSapCriteria();
            b.setBillInSapId(Integer.parseInt(s));
            List<BillInSapDto> billInSapDtoList = billInSapService.findBillInSapDtoList(b);
            for (BillInSapDto bs:billInSapDtoList
                 ) {
                byIds.add(bs);
            }


        }

        //System.out.println(ids);

        model.addAttribute("byids", byIds);
        return prefix + "/print";
    }

    /**
     * sap单据记录
     * @author 李帅辰
     * @date 2021/6/21 17:00
     * @return java.lang.String
     */
    @RequiresPermissions("in:billInSap:view")
    @GetMapping("/billInSapPage")
    public String billInSapPage() {
        return prefix + "/billInSap";
    }

    /**
     *跳转收货单
     * @return
     */
    @RequiresPermissions("in:billInSapTake:view")
    @GetMapping("/billInSapTakePage")
    public String billInSapTakePage() {
        return prefix + "/billInSapTake";
    }




    /**
     *跳转收货单的明细页面
     * @return
     */
    @GetMapping("/billInSapTakeDetail")
    public String billInSapTakeDetail() {
        return prefix + "/billInSapTakeDetail";
    }



    /**
     * sap单据记录
     * @param
     * @return
     */
    //@RequiresPermissions("in:billInSap:findList")
    @PostMapping("/findList")
    @ResponseBody
    public TableDataInfo findList(BillInSapCriteria billInSapCriteria) {
        startPage();
        List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
        return getDataTable(billInSapList);
    }



    /**
     * 导出列表exportTake
     */
    @RequiresPermissions("in:billInSap:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BillInSapCriteria billInSapCriteria) {
        List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
        ExcelUtil<BillInSapDto> util = new ExcelUtil<BillInSapDto>(BillInSapDto.class);
        return util.exportExcel(billInSapList, "Sap单据");
    }
//    @RequiresPermissions("in:billInSap:exportTake")
//    @PostMapping("/exportTake")
//    @ResponseBody
//    public AjaxResult export2(BillInSapCriteria billInSapCriteria) {
//        List<BillInSap> billInSapLisy = billInSapService.findBillInSapList(billInSapCriteria);
//        ExcelUtil<BillInSap> util = new ExcelUtil<BillInSap>(BillInSap.class);
//        return util.exportExcel(billInSapLisy, "收货单");
//    }

    /**
     * 导出列表
     */
//    @RequiresPermissions("in:billInSap:partExcelTake")
//    @PostMapping("/partExcelTake")
//    @ResponseBody
//    public AjaxResult partExcel2(@RequestParam  String ids) {
//        List<BillInSap> byIds=new ArrayList();
//        String[] split = ids.split(",");
//        for (String s:split) {
//            BillInSapCriteria b=new BillInSapCriteria();
//            b.setBillInSapId(Integer.parseInt(s));
//            List<BillInSap> billInSapLisy = billInSapService.findBillInSapList(b);
//            for (BillInSap bs:billInSapLisy) {
//                byIds.add(bs);
//            }
//        }
//        // List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
//        ExcelUtil<BillInSap> util = new ExcelUtil<BillInSap>(BillInSap.class);
//        return util.exportExcel(byIds, "收货单");
//    }





    //打印
//    @RequestMapping("printst")
//    public String printst(@RequestParam String ids, Model model) {
//        List<BillInSap> byIds=new ArrayList();
//        String[] split = ids.split(",");
//        for (String s:split
//        ) {
//            BillInSapCriteria b=new BillInSapCriteria();
//            b.setBillInSapId(Integer.parseInt(s));
//            List<BillInSap> billInSapLisy = billInSapService.findBillInSapList(b);
//            for (BillInSap bs:billInSapLisy
//            ) {
//                byIds.add(bs);
//            }
//
//
//        }
//
//        //System.out.println(ids);
//
//        model.addAttribute("byids", byIds);
//
//
//        return prefix + "/printst";
//    }




    @PostMapping("/findBillInSapDtoById")
    @ResponseBody
    public BillInSapDto findBillInSapDtoById(Integer billInSapId) {
        return billInSapService.findBillInSapDtoById(billInSapId);
    }


}
